package com.hanhanxiaochong.zhongxiangchuanmei.view.home.act;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hanhanxiaochong.zhongxiangchuanmei.R;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.LoginInfoBean;
import com.hanhanxiaochong.zhongxiangchuanmei.bean.ProjectDetailBean;
import com.hanhanxiaochong.zhongxiangchuanmei.presenter.HotProjectDetailPresenter;
import com.hanhanxiaochong.zhongxiangchuanmei.util.CustomWebViewClient;
import com.hanhanxiaochong.zhongxiangchuanmei.util.MessageEvent;
import com.hanhanxiaochong.zhongxiangchuanmei.util.ResourcesUtils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.SharedPreferencesUtil;
import com.hanhanxiaochong.zhongxiangchuanmei.util.Utils;
import com.hanhanxiaochong.zhongxiangchuanmei.util.glide.GlideImgManager;
import com.hanhanxiaochong.zhongxiangchuanmei.view.base.BaseActivity;
import com.hanhanxiaochong.zhongxiangchuanmei.view.iview.IHotProjectDetailView;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.StarBar;
import com.hanhanxiaochong.zhongxiangchuanmei.widget.WrapLinearLayout;
import com.wzgiceman.rxretrofitlibrary.retrofit_rx.http.RetrofitSource;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

/**
 * Author : 贾桐
 * E-mail : 653773284@qq.com
 * Time   : 2018/5/2.
 * Desc   :
 */

public class HotProjectDetailActivity extends BaseActivity<HotProjectDetailPresenter> implements IHotProjectDetailView {

    @BindView(R.id.img_share)
    ImageView imgShare;
    @BindView(R.id.img_favorite)
    ImageView imgFavorite;
    @BindView(R.id.iv_self_support)
    ImageView ivSelfSupport;
    @BindView(R.id.tv_good_name)
    TextView tvGoodName;
    @BindView(R.id.tv_vip_price)
    TextView tvVipPrice;
    @BindView(R.id.iv_becom_vip)
    ImageView ivBecomVip;
    @BindView(R.id.tv_service_price)
    TextView tvServicePrice;
    @BindView(R.id.tv_project_time)
    TextView tvProjectTime;
    @BindView(R.id.ll_fit_container)
    WrapLinearLayout llFitContainer;
    @BindView(R.id.ll_attention_container)
    LinearLayout llAttentionContainer;
    @BindView(R.id.ll_step_container)
    LinearLayout llStepContainer;
    @BindView(R.id.ll_product_container)
    LinearLayout llProductContainer;
    @BindView(R.id.tv_html_detail)
    WebView tvHtmlDetail;
    @BindView(R.id.good_star)
    StarBar goodStar;
    @BindView(R.id.tv_good_score)
    TextView tvGoodScore;
    @BindView(R.id.tv_good_evaluation)
    TextView tvGoodEvaluation;
    @BindView(R.id.iv_call)
    ImageView ivCall;
    @BindView(R.id.tv_subscribe)
    TextView tvSubscribe;
    @BindView(R.id.rl_bottom)
    LinearLayout rlBottom;
    @BindView(R.id.iv_project_pic)
    ImageView ivProjectPic;
    @BindView(R.id.tv_normal_price)
    TextView tvNormalPrice;

    private String phone;
    private String project_id;
    private String token;
    private String u_id;

    public static Intent createIntent(Context context, String id) {
        Intent intent = new Intent(context, HotProjectDetailActivity.class);
        intent.putExtra("id", id);
        return intent;
    }

    @Override
    protected void initView() {
        setContentView(R.layout.activity_hotproject_detail);
        EventBus.getDefault().register(this);
        LoginInfoBean loginInfo = SharedPreferencesUtil.getsInstances(this).getLoginInfo();
        token = loginInfo.getToken();
        u_id = loginInfo.getU_id();
    }

    @Override
    protected void initPresenter() {
        project_id = getIntent().getStringExtra("id");
        mPresenter = new HotProjectDetailPresenter(this);
    }

    @Override
    protected void init() {
        mPresenter.getProjectInfo(project_id);
    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void setData(ProjectDetailBean data) {
        imgFavorite.setSelected(!data.getSf_num().equals("0"));
        GlideImgManager.glideLoader(this, RetrofitSource.image_url + data.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, ivProjectPic);
        tvGoodName.setText(data.getName());
        ivSelfSupport.setVisibility(data.getSelf_support().equals("y") ? View.VISIBLE : View.GONE);
        tvVipPrice.setText(String.format(ResourcesUtils.getString(R.string.vip_good_price), data.getPrice_vip()));
        tvNormalPrice.setText(String.format(ResourcesUtils.getString(R.string.normal_good_price), data.getPrice()));
        tvServicePrice.setText(String.format(ResourcesUtils.getString(R.string.service_price), data.getService_price()));
        tvProjectTime.setText(String.format(ResourcesUtils.getString(R.string.minute), data.getWhen_long()));

        for (ProjectDetailBean.SymptomListsBean bean : data.getSymptom_lists()) {
            View view = ResourcesUtils.inflate(R.layout.rl_text_tag);
            TextView tag = view.findViewById(R.id.tv_tag);
            tag.setText(bean.getName());
            llFitContainer.addView(view);
        }

        for (ProjectDetailBean.AttentionListsBean bean : data.getAttention_lists()) {
            View view = ResourcesUtils.inflate(R.layout.rl_text_tag);
            TextView tag = view.findViewById(R.id.tv_tag);
            tag.setText(bean.getName());
            llAttentionContainer.addView(view);
        }

        for (ProjectDetailBean.StepBean bean : data.getStep()) {
            View view = ResourcesUtils.inflate(R.layout.rl_pic);
            ImageView pic = view.findViewById(R.id.iv_pic);
            TextView step = view.findViewById(R.id.tv_step);
            GlideImgManager.glideLoader(this, RetrofitSource.image_url + bean.getPic(), R.mipmap.img_error, R.mipmap.img_error, pic);
            step.setText(bean.getContent());
            System.out.println(RetrofitSource.image_url + data.getPic());
            llStepContainer.addView(view);
        }

        for (ProjectDetailBean.ProductBean bean : data.getProduct()) {
            View view = ResourcesUtils.inflate(R.layout.rl_pic);
            ImageView pic = view.findViewById(R.id.iv_pic);
            TextView step = view.findViewById(R.id.tv_step);
            GlideImgManager.glideLoader(this, RetrofitSource.image_url + bean.getPic().split(",")[0], R.mipmap.img_error, R.mipmap.img_error, pic);
            step.setText(bean.getName());
            llProductContainer.addView(view);
        }

        //富文本信息
        String html = data.getIntro();
        tvHtmlDetail.setWebViewClient(new CustomWebViewClient());
        WebSettings webSettings = tvHtmlDetail.getSettings();
        //允许JS执行
        webSettings.setJavaScriptEnabled(true);
        //listview,webview中滚动拖动到顶部或者底部时的阴影
        tvHtmlDetail.setOverScrollMode(View.OVER_SCROLL_NEVER);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //默认不使用缓存
        webSettings.setDefaultTextEncodingName("utf-8");
        tvHtmlDetail.loadData(html, "text/html; charset=UTF-8", null);//这种写法可以正确解码

        phone = data.getTelep();

        goodStar.setStarMark(Float.parseFloat(data.getScore()));
        tvGoodScore.setText(String.format(ResourcesUtils.getString(R.string.good_score), data.getScore()));
        tvGoodEvaluation.setText(String.format(ResourcesUtils.getString(R.string.good_evaluation), data.getSt_num()));
    }

    @Override
    public void collectSuccess() {
        imgFavorite.setSelected(true);
    }

    @Override
    public void cancelCollectSuccess() {
        imgFavorite.setSelected(false);
    }

    @OnClick({R.id.ll_back, R.id.img_share, R.id.img_favorite, R.id.iv_call, R.id.tv_subscribe, R.id.iv_becom_vip
            , R.id.tv_good_evaluation})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_back:
                finish();
                break;
            case R.id.img_share:
                final String url = "http://gxcm.quan-oo.com/index/users/translate?uid=" + u_id;
                OnekeyShare oks = new OnekeyShare();
                //关闭sso授权
                oks.disableSSOWhenAuthorize();
                // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间等使用
                oks.setTitle(getString(R.string.app_name));
                // titleUrl是标题的网络链接，QQ和QQ空间等使用
                oks.setTitleUrl(url);
                // url仅在微信（包括好友和朋友圈）中使用
                oks.setUrl(url);
                oks.setShareContentCustomizeCallback((platform, paramsToShare) -> {
                    paramsToShare.setText(getString(R.string.app_name));
                    paramsToShare.setText("我分享了一个动态");
                    if (Wechat.NAME.equals(platform.getName())) {
                        paramsToShare.setShareType(Platform.SHARE_WEBPAGE);
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (QQ.NAME.equals(platform.getName())) {
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    } else if (SinaWeibo.NAME.equals(platform.getName())) {
                        paramsToShare.setTitleUrl(url);
                        paramsToShare.setTitle(getString(R.string.app_name));
                    }
                });
                // 启动分享GUI
                oks.show(this);
//                ShareDialog shareDialog = new ShareDialog(mContext);
//                shareDialog.show();
                break;
            case R.id.img_favorite:
                if (imgFavorite.isSelected()) {
                    mPresenter.cancelCollectShop(token, project_id);
                } else {
                    mPresenter.collectShop(token, project_id);
                }
                break;
            case R.id.iv_call:
                if (phone != null)
                    Utils.callPhone(this, phone);
                break;
            case R.id.tv_subscribe:
                startActivity(ChooseShopActivity.createIntent(this, project_id, "1"));
                break;
            case R.id.iv_becom_vip:
                startActivity(HomeVipActivity.createIntent(this));
                break;
            case R.id.tv_good_evaluation:
                startActivity(EvaluationListActivity.createIntent(this, 1, project_id));
                break;
        }
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void handleEvent(MessageEvent event){
        if (event.getMessage().equals("pay_success")){
            finish();
        }
    }
}
